﻿using System;
using MediatR;
using Casamiel.Domain.Response;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Domain;
using Newtonsoft.Json;

namespace Casamiel.Application.Commands.Staff
{
	/// <summary>
	/// 
	/// </summary>
	public sealed class ModifyPasswordCommandHandler:IRequestHandler<ModifyPasswordCommand,BaseResult<string>>
	{
		private readonly IHlEmployeeRepository _hlEmployeeRepository;
		private readonly IHLLoginRepository _hLLoginRepository;
		private readonly IMemberAccessTokenRepository _memberAccessTokenRepository;

		/// <summary>
		/// 
		/// 
		/// </summary>
		/// <param name="hlEmployeeRepository"></param>
		/// <param name="hLLoginRepository"></param>
		/// <param name="memberAccessTokenRepository"></param>
		public ModifyPasswordCommandHandler(IHlEmployeeRepository hlEmployeeRepository, IHLLoginRepository hLLoginRepository,IMemberAccessTokenRepository  memberAccessTokenRepository)
		{
			_hlEmployeeRepository = hlEmployeeRepository;
			_hLLoginRepository = hLLoginRepository;
			_memberAccessTokenRepository = memberAccessTokenRepository;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="request"></param>
		/// <param name="cancellationToken"></param>
		/// <returns></returns>
		public async Task<BaseResult<string>> Handle(ModifyPasswordCommand request, CancellationToken cancellationToken)
		{
			if (request == null) {
				throw new ArgumentNullException(nameof(request));
			}
			Console.WriteLine($"{JsonConvert.SerializeObject(request)}");
			var loginentity = await _hLLoginRepository.FindAsync<ICasaMielSession>(request.Mobile).ConfigureAwait(false);
			if (loginentity == null) {
				return new BaseResult<string>("", 9999, "用户信息不存在");
			}

			var password = Common.Utilities.SecurityUtil.EncryptText(request.OldPassword, loginentity.PasswordSalt);
			if (password != loginentity.Password) {
				return new BaseResult<string>("", 9999, "旧密码不对");
			}

			var passwordSalt = $"{Guid.NewGuid().GetHashCode()}";

			loginentity.PasswordSalt = passwordSalt;
			loginentity.Password = Common.Utilities.SecurityUtil.EncryptText(request.Password, passwordSalt);
			await _hLLoginRepository.UpdateAsync<ICasaMielSession>(loginentity).ConfigureAwait(false);
			var accesstoken = await _memberAccessTokenRepository.FindAsync<ICasaMielSession>(request.Mobile, 5).ConfigureAwait(false);
			if (accesstoken != null) {
				accesstoken.Access_Token = "";
				await _memberAccessTokenRepository.UpdateAsync<ICasaMielSession>(accesstoken).ConfigureAwait(false);
			}
			return new BaseResult<string>("", 0, "密码修改成功"); 
		}
	}
}
